<template>
  <div>
    <div class="flex items-center mb-2 gap-2">
      <div>{{ editorTitle }}</div>
      <el-button
        type="primary"
        circle
        size="small"
        @click="addOption"
        :icon="Plus"
      />
    </div>
    <div class="flex flex-col gap-2">
      <div
        class="flex items-center gap-2"
        v-for="(item, index) in options"
        :key="index"
      >
        <el-input
          :ref="(el) => setInputRef(el, index)"
          v-model="options[index]"
          :placeholder="`请输入${editorTitle}`"
        />
        <el-button
          type="danger"
          circle
          size="small"
          class="ml-2"
          @click="deleteOption(index)"
          :icon="Minus"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { Component } from "vue";
import { Minus, Plus } from "@element-plus/icons-vue";
import type { IUpdateStatus } from "@/types/common";

const props = defineProps<{
  id: string;
  status: string[];
  isShow: boolean;
  name: string;
  statusKey: string;
  editCom: Component;
  currentStatusIndex: number;
  editorTitle: string;
}>();

const updateStatus = inject("updateStatus") as IUpdateStatus;

const options = ref<string[]>(props.status);
const inputRefs = ref<any[]>([]);

// - 设置input引用
const setInputRef = (el: any, index: number) => {
  if (el) {
    inputRefs.value[index] = el;
  }
};

// * 添加选项
const addOption = () => {
  // - 先添加一个选项
  updateStatus(props.statusKey);

  // ? 在下一个tick聚焦到新添加的input
  nextTick(() => {
    const lastInput = inputRefs.value.at(-1);

    if (lastInput && lastInput.focus) {
      // - 选中所有文本
      lastInput.select();
      // - 聚焦
      lastInput.focus();
    }
  });
};

// * 删除选项
const deleteOption = (index: number) => {
  updateStatus(props.statusKey, index);
};
</script>

<style scoped></style>
